<%@ include file="/taglibs.jsp" %>
<%@ page import="java.lang.Throwable,
				java.sql.Connection,
				java.sql.SQLException,
				java.sql.Statement,
				java.util.ArrayList,
				java.util.HashMap,
				java.util.List,
				java.util.Map,
				org.jawa.util.*,
				org.jawa.Constants,
				org.jawa.database.*,
				java.io.File,
				
				org.springframework.context.ApplicationContext,
				org.springframework.web.context.support.WebApplicationContextUtils,				
				org.springframework.security.providers.encoding.ShaPasswordEncoder"
%>

<%
	// Get parameters //
	boolean save = ParamUtils.getBooleanParameter(request,"save");
    String username = ParamUtils.getParameter(request,"username");
    String email = ParamUtils.getParameter(request,"email");
    String password = ParamUtils.getParameter(request,"password");
    String passwordConfirm = ParamUtils.getParameter(request,"passwordConfirm");

    Map<String, String> errors = new HashMap<String, String>();
   	ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
   	ShaPasswordEncoder passwordEncoder=(ShaPasswordEncoder)ctx.getBean("passwordEncoder");
   	
    
    // Handle a request to create a user:
    if (save) {
        // Validate
        if (username == null) {
            errors.put("username","");
        }
        else {
            try {
                username = username.trim().toLowerCase();
            }
            catch (Exception se) {
                errors.put("username", "");
            }
        }
        // Trim the password. This means we don't accept spaces as passwords. We don't
        // trim the passwordConfirm as well since not trimming will ensure the user doesn't
        // think space is an ok password character.
        if (password == null || password.trim().equals("")) {
            errors.put("password","");
        }
        if (passwordConfirm == null) {
            errors.put("passwordConfirm","");
        }
        if (password != null && passwordConfirm != null && !password.equals(passwordConfirm)) {
            errors.put("passwordMatch","");
        }
        if(email==null || email.trim().equals("")){
        	errors.put("email","");
        }

        // do a create if there were no errors
        if (errors.size() == 0) {
            try {
                //保存数据
                org.jawa.model.User user=new  org.jawa.model.User();
                user.setUsername(username);
                user.setEmail(email);
                user.setPassword(password);
                user.setLastlogindate(new java.util.Date());
                
                String className = Constants.getXMLProperty("connectionProvider.className");
                ConnectionProvider connectionProvider ;
				if (className != null) {
					// Attempt to load the class.
					try {
						 Class conClass = ClassUtils.forName(className);
						 connectionProvider = ((ConnectionProvider) conClass
								.newInstance());
						 connectionProvider.start();
						 Connection conn = connectionProvider.getConnection();
						 Statement stmt = conn.createStatement();
						 stmt.execute("delete from user where userName='admin';");
						 stmt.execute("insert into user(username,email,password,regdate,enabled) values('"+username+"','"+email+"','"+passwordEncoder.encodePassword(password,null)+"','2008-12-05',true);");
						 conn.close();
					} catch (Exception e) {
						e.printStackTrace();
						//出错，请重设数据库
						errors.put("database"," Please Set Database ");
					}
					
				}else{
					//出错，请重设数据库
					errors.put("database"," Please Set Database ");
				}
            }/*
            catch (AlreadyExistsException e) {
                errors.put("usernameAlreadyExists","");
            }*/
            catch (Exception e) {
                errors.put("general","Can't create Admin");
            }
        }
    }
%>
<html>
<head>
<title><fmt:message key="setup.user.settings.title" /></title>
<meta name="currentStep" content="5"/>
</head>
<body>
	<h1>
       <fmt:message key="setup.user.settings.title" />
	</h1>
	<p>
	    <fmt:message key="setup.user.settings.title"/>
	</p>
	<%  if (!errors.isEmpty() && save) { %>

    <div class="error">
	    <table cellpadding="0" cellspacing="0" border="0">
		    <tbody>
		        <tr>
		            <td class="jawa-icon-label">
		
		            <% if (errors.get("general") != null) { %>
		                <fmt:message key="user.create.error_creating_account" />
		            <% } else if (errors.get("username") != null) { %>
		                <fmt:message key="user.create.invalid_username" />
		            <% } else if (errors.get("usernameAlreadyExists") != null) { %>
		                <fmt:message key="user.create.user_exist" />		            
		            <% } else if (errors.get("email") != null) { %>
		                <fmt:message key="user.create.invalid_email" />
		            <% } else if (errors.get("password") != null) { %>
		                <fmt:message key="user.create.invalid_password" />
		            <% } else if (errors.get("passwordMatch") != null) { %>
		                <fmt:message key="user.create.invalid_match_password" />
		            <% } else if (errors.get("passwordConfirm") != null) { %>
		                <fmt:message key="user.create.invalid_password_confirm" />
		            <% } else if (errors.get("database") != null) { %>
		                <fmt:message key="user.create.database" />
		            <% } %>
		            </td>
		        </tr>
		    </tbody>
	    </table>
    </div>

	<%  } else if(errors.isEmpty()&& save){
			response.sendRedirect("setup-finish.jsp");
			return;
		}
	%>
	<!-- BEGIN jawa-contentBox -->
	<div class="jawa-contentBox">
			<form name="f" action="setup-admin-settings.jsp" method="post">
				<input type="hidden" name="save" value="true">
				<div class="jawa-contentBoxHeader">
					<fmt:message key="user.create.new_user" />
				</div>
				<div class="jawa-contentBox">
					<table cellpadding="3" cellspacing="0" border="0">
						<tbody>
							<tr>
								<td width="1%" nowrap><label for="usernametf"><fmt:message key="user.create.username" /></label> *</td>
								<td width="99%">
									<input type="text" name="username" size="30" maxlength="75" 
									 id="usernametf" autocomplete="off">
								</td>
							</tr>
							<tr>
								<td width="1%" nowrap>
									<label for="emailtf"><fmt:message key="user.create.email" /></label></td>
								<td width="99%">
									<input type="text" name="email" size="30" maxlength="75"
									 id="emailtf">
								</td>
							</tr>
							<tr>
								<td nowrap>
									<label for="passtf"><fmt:message key="user.create.password" /></label> *
								</td>
								<td width="99%">
									<input type="password" name="password" value="" size="20" maxlength="75"
									 id="passtf">
								</td>
							</tr>
							<tr>
								<td width="1%" nowrap>
									<label for="confpasstf"><fmt:message key="user.create.confirm_pwd" /></label> *
								</td>
								<td width="99%">
									<input type="password" name="passwordConfirm" value="" size="20" maxlength="75"
									 id="confpasstf">
								</td>
							</tr>				        
					                
						</tbody>
					</table>			
				</div>
				<span class="jawa-description">
			    * <fmt:message key="user.create.requied" />
			    </span>

				<div align="right">
					<input type="submit" name="save" value="<fmt:message key="button.continue" />" id="jawa-setup-save" border="0">
				</div>
			</form>
	</div>
	<!-- END jawa-contentBox -->
</body>
</html>
